package com.mccken.demo.io.nio;

import java.nio.ByteBuffer;

import static com.mccken.demo.io.util.ByteBufferUtil.debugAll;

/**
 * 黏包、半包
 * 
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2023-11-05 22:44
 **/
public class NIO_5 {

	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(32);
		// 模拟黏包
		buffer.put("Hello,world\nI'm zhangsan\nHo".getBytes());
		
		debugCurr(buffer);
		
		split(buffer);
		// 模拟半包
		buffer.put("w are you?\nI'm li".getBytes());
		split(buffer);
	}

	private static void debugCurr(ByteBuffer buffer) {

		for (int i = 0; i < buffer.limit(); i++) {
			byte b = buffer.get(i);
			char c = (char) b;
			System.out.println(i + " -> " + c+ " -> " + b);	
		}
		
	}

	
	private static void split(ByteBuffer buffer) {
		// 切换到读模式
		buffer.flip();
		int oldLimit = buffer.limit();

		for (int i = 0; i < oldLimit; i++) {
			if(buffer.get(i) == '\n') {
				System.out.println(i);
				System.out.println((char)buffer.get(i));

				int capacity = i - buffer.position()+1 ;
				System.out.println("capacity:" + capacity);
				ByteBuffer target = ByteBuffer.allocate(capacity);
				System.out.println("buffer init: position:" + buffer.position() + " limit:" + buffer.limit() + " capacity:" + buffer.capacity());
				buffer.limit(i+1);
				target.put(buffer);


				System.out.println("buffer put: position:" + buffer.position() + " limit:" + buffer.limit() + " capacity:" + buffer.capacity());
				System.out.println(("byte:" + buffer.get(buffer.position()-1)));
				System.out.println("target");
				debugAll(target);

//				ByteBuffer target2 = ByteBuffer.allocate(i - buffer.position() + 1);
//				buffer.limit(i+1);
//				target2.put(buffer);
//				debugAll(target2);
				
				buffer.limit(oldLimit);
				System.out.println((char)buffer.get(buffer.position()));
				System.out.println("===============");
			}
		}
		buffer.compact();
//		System.out.println("compact");
		
	}
}
